/**
 * Created by ayu on 2017/6/10.
 */
let sql = require ('../utils/DB/MysqlStatement');
let logger = require ('../utils/logger/Logger');

Date.prototype.Format = function ( fmt )
{ //author: meizz
    let o = {
        "M+": this.getMonth () + 1,                 //月份
        "d+": this.getDate (),                    //日
        "h+": this.getHours (),                   //小时
        "m+": this.getMinutes (),                 //分
        "s+": this.getSeconds (),                 //秒
        "q+": Math.floor ((this.getMonth () + 3) / 3), //季度
        "S" : this.getMilliseconds ()             //毫秒
    };
    if (/(y+)/.test (fmt))
    {
        fmt = fmt.replace (RegExp.$1, (this.getFullYear () + "").substr (4 - RegExp.$1.length));
    }
    for (let k in o)
        if (new RegExp ("(" + k + ")").test (fmt))
        {
            fmt = fmt.replace (RegExp.$1, (RegExp.$1.length == 1) ? (o[ k ]) : (("00" + o[ k ]).substr (("" + o[ k ]).length)));
        }
    return fmt;
};

module.exports = {
    /**
     * 就地端原始数据上报，批量插入
     * @param _params
     * @param callBack
     */
    insertRawDatas                     : function ( _params, callBack )
    {
        let [
                session_code           = '', //场次编码
                session_start_datetime = '', //场次开始时间
                session_end_datetime   = '', //场次结束时间
                net_agent_fee          = '0', //服务费。（网络代售服务费）
                audience_count         = '0', //观影人数
                service_fee            = '0', //包场费。（房间费用）
                relation_sales         = '0', //关联收入。（酒水、餐饮、零售商品等）
                ad_sales               = '0', //广告收入。（广告费用）
                other_sales            = '0', //其它收入（综合其它收入）
                business_date          = '', //营业时间
                screen_code            = '', //影厅
                programme_sales        = '0',//视听节目费用
                programme_other_sales  = '0' //视听节目其它收入
            ]                          =
                [
                    _params.session_code,
                    _params.session_start_datetime,
                    _params.session_end_datetime,
                    _params.net_agent_fee,
                    _params.audience_count,
                    _params.service_fee,
                    _params.relation_sales,
                    _params.ad_sales,
                    _params.other_sales,
                    _params.business_date,
                    _params.screen_code,
                    _params.programme_sales,
                    _params.programme_other_sales
                ];
        let data = _params.data;
        let sqlStr = 'insert into sarft_playinfo (client_id,openid,cid,tid,mid,uuid,type,valid_status,endtime,playedduration,createtime,session_code,session_start_datetime,session_end_datetime,net_agent_fee,audience_count,service_fee,relation_sales,ad_sales,other_sales,business_date,screen_code,has_seen,programme_sales,programme_other_sales) ' +
            'values(?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?)';
        let arr = [];
        data.forEach (function ( value, index )
        {
            if (index >= 1)//批量插入
            {
                sqlStr += ',(?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?)';
            }
            //为微信用户足迹查询接口封装处理日期
            let time = _params.session_end_datetime||Date.now();
            let endtime = new Date (time).Format ('yyyy-MM-dd hh:mm');
            let [ id = '', openid = '', cid = '', tid = '', mid = '', uuid = '', type = '', status = 0 ]
                     =
                    [ value.id, value.openid, value.cid, value.tid, value.mid, value.uuid, value.type ];
            let [ playedduration = '', createtime = '', has_seen = 0 ] = [ value.playedduration, value.createtime, value.has_seen ];
            if (parseInt (playedduration) >= 0)
            {
                arr.push (id, openid, cid, tid, mid, uuid, type, status, endtime, playedduration, createtime, session_code, session_start_datetime, session_end_datetime, net_agent_fee, audience_count, service_fee, relation_sales, ad_sales, other_sales, business_date, screen_code, 1, programme_sales, programme_other_sales);
            }
            else
            {
                arr.push (id, openid, cid, tid, mid, uuid, type, 1, endtime, playedduration, createtime, session_code, session_start_datetime, session_end_datetime, net_agent_fee, audience_count, service_fee, relation_sales, ad_sales, other_sales, business_date, screen_code, 2, programme_sales, programme_other_sales);
            }
            if ((index + 1) === data.length)
            {
                sql.sqlStatement ([ sqlStr, arr ], function ( done )
                {
                    if (done.isSuccess)
                    {
                        callBack ({
                            isSuccess   : true,
                            result      : done.result,
                            session_code: session_code
                        });
                    }
                    else
                    {
                        logger.error ('影厅：' + cid + ',场次：' + session_code + '。数据库插入失败');
                        callBack ({
                            isSuccess   : false,
                            session_code: session_code
                        });
                    }
                });
            }
        });
    },
    /**
     * 改变上报状态
     * @param _params
     * @param callBack
     */
    updateRawDataStatusBySessionCode   : function ( _params, callBack )
    {
        let sqlStr = 'UPDATE sarft_playinfo set upload_status = ? where session_code = ?';
        let arr = Array.from ([ _params.status, _params.session_code ]);
        sql.sqlStatement ([ sqlStr, arr ], function ( done )
        {
            if (done.isSuccess)
            {
                callBack ({
                    isSuccess   : true,
                    result      : done.result,
                    session_code: _params.session_code
                });
            }
            else
            {
                logger.error ('场次：' + _params.session_code + ' 更新上报状态' + _params.status + '失败');
                callBack ({
                    isSuccess   : false,
                    session_code: _params.session_code
                });
            }
        });
    },
    updataRawDataPacket_idBySessionCode: function ( _params, callBack )
    {
        let sqlStr = 'update sarft_playinfo set packet_id = ? where session_code = ?';
        let arr = Array.from (_params);
        sql.sqlStatement ([ sqlStr, arr ], function ( done )
        {
            if (done.isSuccess)
            {
                callBack ({
                    isSuccess: true
                });
            }
            else
            {
                callBack ({
                    isSuccess: false
                });
            }
        });
    },
    findRawDataByHas_seen              : function ( _params, callBack )
    {
        let sqlStr = 'select count(*) as count from sarft_playinfo where session_code = ? and has_seen = 1';
        let arr = [ _params ];
        sql.sqlStatement ([ sqlStr, arr ], function ( done )
        {
            if (done.isSuccess)
            {
                callBack ({
                    isSuccess: true,
                    count    : done.result[ 0 ].count
                });
            }
            else
            {
                callBack ({
                    isSuccess: false
                });
            }
        });
    }
};